package com.demo.listener;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author WuLiangHang
 */
@WebServlet(name = "DownloadServlet", urlPatterns = "/download.do")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        String fileName = request.getParameter("path");
        //GET请求中，参数中包含了中文 需要自己动手转换
        String filePath = "D:\\download\\" + fileName;
        File file = new File(filePath);
        if (!file.exists()) {
            response.getWriter().print("您要下载的文件不存在！");
            return;
        }
        fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
        response.addHeader("content-disposition", "attachment;filename=" + fileName);
        //将输入流读取到的文件字节流，交给响应的字节输出流 传递给客户端
        IOUtils.copy(new FileInputStream(file), response.getOutputStream());
    }
}
